import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// 权限判断指令
import permission from '@/directive/permission/index.js'
import { getClubType } from '@/api/clubType'
import { getClubList, getClubDetail } from '@/api/club'
import { getFacultyList } from '@/api/school'
import { createClubApply } from '@/api/clubApply'
import { getToken } from '@/utils/auth'

// 默认查询条件
const defaultListQuery = {
  page: 1,
  limit: 10,
  ordering: '-id',
  name: undefined,
  type: undefined,
  president: undefined
}

const defaultForm = {
  id: undefined,
  name: undefined,
  is_active: true
}

const defaultClubApplyForm = {
  club_id: undefined,
  reason: undefined,
  file: []
}

export default {
  components: { Pagination },
  directives: { permission },
  filters: {
    activeTextFilter(type) {
      const typeMap = {
        true: '启用',
        false: '禁用'
      }
      return typeMap[type]
    },
    activeStyleFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      total: 0,
      listQuery: Object.assign({}, defaultListQuery),
      listLoading: false,
      dataList: [],
      clubSelectList: [],
      clubTypeList: [],
      facultyList: [],
      dialogViewFormVisible: false,
      dialogStatus: '',
      dialogText: '',
      form: Object.assign({}, defaultForm),
      previewImg: false,

      headers: { Authorization: 'Bearer ' + getToken() },
      fileLimitCnt: 1,
      fileLimitSize: 5,
      elUploadUrl: process.env.VUE_APP_BASE_API + 'api/upload/upload_img/',
      elData: { dir_name: 'club_apply' },

      clubApplyForm: JSON.parse(JSON.stringify(defaultClubApplyForm)),
      clubApplyDialog: false,
      clubApplyRules: {
        reason: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        file: [{ required: true, message: '文件必须上传', trigger: 'change' }]
      }

    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getClubType()
      this.getList()
      this.getFacultyList()
    },

    // 获取表格数据
    getList() {
      this.listLoading = true
      getClubList(this.listQuery).then(res => {
        this.dataList = res.results
        this.total = res.count
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // 搜索事件
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 重置区域搜索条件
    resetFilter() {
      this.listQuery = Object.assign({}, defaultListQuery)
    },

    // 获取社团分类下拉框列表
    getClubType() {
      getClubType({ is_active: true }).then(res => {
        this.clubTypeList = res
      })
    },

    getFacultyList() {
      getFacultyList().then(res => {
        this.facultyList = res.data
      })
    },

    // 点击查看详情
    showViewDialog(row) {
      const loading = this.$loading({
        lock: true,
        text: '正在获取数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      getClubDetail(row.id).then(res => {
        loading.close()
        this.form = res
        this.form.first_check_status = ''
      }).catch((error) => {
        this.$message.error(error.response.data.message)
      })
      // this.form = Object.assign({}, row)
      this.dialogStatus = 'view'
      this.dialogText = row.title
      this.dialogViewFormVisible = true
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },

    // 点击申请加入
    showClubApplyDialog(row) {
      this.clubApplyForm.club_id = row.id
      this.clubApplyDialog = true
      this.$nextTick(() => {
        this.$refs['clubApplyForm'].clearValidate()
      })
    },
    // 进行创建申请加入
    createClubApply() {
      this.$refs['clubApplyForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          createClubApply(this.clubApplyForm).then(response => {
            loading.close()
            this.clubApplyDialog = false
            this.$notify({
              title: '成功',
              message: '提交成功',
              type: 'success',
              duration: 2000
            })
          }).catch((error) => {
            loading.close()
            this.$notify({
              title: '失败',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        } else {
          console.log('表单出错')
        }
      })
    },

    // 上传文件之前的钩子
    beforeUpload(file, typeName, limit = 10) {
      // 限制文件上传大小, 大于1M则提示, 且不请求提交表单
      const flag = file.size / 1024 / 1024 < limit
      if (!flag) {
        this.$message.error('上传文件大小不能超过' + limit + 'M')
        return false
      }
    },
    // 上传文件数量超出自定义数量
    handleExceed(files, fileList) {
      this.$message.warning('已达到最大上传数量, 请删除后继续上传')
    },
    handleProgress(event, file, fileList) {
      this.loading = true
      this.loadingText = '正在上传文件....'
    },
    // 上传成功回调
    handleSuccess(response, typeName) {
      this.loading = false
      this.$message({
        message: '上传文件成功',
        type: 'success'
      })
      if (typeName === 'club_apply_file') {
        this.clubApplyForm.file.push(response)
        this.$refs.clubApplyForm.validateField('file')
      }
    },
    // 上传失败
    handleError(res_error, file, fileList) {
      this.loading = false
      this.$message({
        message: '上传文件失败',
        type: 'danger'
      })
    },
    // 文件列表移除文件
    handleRemove(file, typeName) {
      let key = ''
      if (file.response) {
        key = file.response.data
      } else {
        key = file.url
      }
      var i = 0
      if (typeName === 'club_apply_file') {
        for (i = 0; i < this.clubApplyForm.file.length; i++) {
          if (key.indexOf(this.clubApplyForm.file[i].data) !== -1) {
          // if (key.match(this.clubApplyForm.file[i].data)) {
            this.clubApplyForm.file.splice(i, 1)
            break
          }
        }
      }
    },

    // 预览图片
    previewImage(file) {
      this.previewImg = true
      this.imgUrl = file.url
      // this.$refs.viewer.$viewer.show()
    }

  }
}
